package luren.king.wechatlite.ui;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import luren.king.wechatlite.R;
import luren.king.wechatlite.adapter.MessageAdapter;
import luren.king.wechatlite.config.Config;
import luren.king.wechatlite.database.MessageHelper;
import luren.king.wechatlite.pojo.Message;

public class MessageFragment extends Fragment {

    RecyclerView recyclerView;

    @SuppressLint("MissingInflatedId")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载fragment_message布局文件
        View view = inflater.inflate(R.layout.fragment_message,container,false);

        // 获取recyclerView组件
        recyclerView = view.findViewById(R.id.msg_recyclerview);
        Config.RECYCLER_VIEW = recyclerView;

        // 创建LinearLayoutManager对象，用于管理recyclerView的布局
        LinearLayoutManager manager = new LinearLayoutManager(getContext());

        // 设置recyclerView的布局管理器
        recyclerView.setLayoutManager(manager);

        // 设置recyclerView的滚动方向为垂直
        manager.setOrientation(RecyclerView.VERTICAL);

        // 为recyclerView添加分割线装饰
        recyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), 1));

        // 判断recyclerView是否不为空
        if (recyclerView != null){

//            MessageHelper helper = new MessageHelper(getContext());
//            List<Message> list = helper.getAllMessages();
            List<Message> list = new ArrayList<>();
            Message msg = new Message();
            msg.setMessage("消息预览");
            msg.setName("聊天对象");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                msg.setTime(LocalDate.now().toString());
            }
            list.add(msg);

            // 创建MessageAdapter对象，用于展示消息列表
            MessageAdapter adapter = new MessageAdapter(getContext(), list);

            //Config.CHAT_ADAPTER = adapter;
            //直接传给WebSocketClient对象，用于更新消息列表
            Config.WEB_SOCKET.setMainActInfo(adapter, list);

            // 将适配器设置给recyclerView
            recyclerView.setAdapter(adapter);
        }

        Config.WEB_SOCKET.setRecyclerView(Config.RECYCLER_VIEW, null, null, Config.MAIN_ACTIVITY);

        // 返回加载的布局视图
        return view;
    }

}
